import getUserTempId from '@/utils/userTempId';
import { getUserInfo, userLogin } from '@/api';

export default {
  namespaced: true,
  state: {
    userTempId: getUserTempId(),
    token: localStorage.getItem('token') || '',
    userinfo: {},
  },
  getters: {
    userinfo: ({ userinfo }) => userinfo,
    token: ({ token }) => token,
  },
  mutations: {
    SET_USERINFO (state, { userinfo }) {
      state.userinfo = userinfo;
    },
    SET_USER_TOKEN (state, token) {
      localStorage.setItem('token', token);
      state.token = token;
    },
  },
  actions: {
    async userLogin ({ commit, dispatch }, { userinfo }) {
      const { token } = await userLogin(userinfo);
      commit('SET_USER_TOKEN', token);
      dispatch('getUserinfo');
    },
    async userLogout ({ commit }) {
      commit('SET_USER_TOKEN', '');
      commit('SET_USERINFO', '');
    },
    async getUserinfo ({ commit }) {
      const userinfo = await getUserInfo();
      commit('SET_USERINFO', { userinfo });
    },
  },
};
